import { createSlice } from '@reduxjs/toolkit';
import { getUserTokenAPI, getUserInfoAPI } from '@/apis/user';
import { setStorage, getStorage } from '@/utils';

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getStorage('token') || '',
    refresh_token: getStorage('refresh_token') || '',
    userInfo: JSON.parse(getStorage('userInfo') || '{}')
  },
  // 同步修改状态
  reducers: {
    /**
     * @param {object} state initialState 中的数据
     * @param {object} action 修改配置对象
     */
    setToken(state, action) {
      const { token, refresh_token } = action.payload;
      state.token = token;
      state.refresh_token = refresh_token;
      setStorage('token', token);
      setStorage('refresh_token', refresh_token);
    },
    /** 设置用户信息 */
    setUserInfo(state, { payload }) {
      state.userInfo = payload;
      setStorage('userInfo', JSON.stringify(payload));
    },
    /** 退出登录，清空用户信息 */
    onLogout(state) {
      state.token = '';
      state.refresh_token = '';
      state.userInfo = {};
    }
  }
});

export const { setToken, setUserInfo, onLogout } = userStore.actions;

// 登录获取token及用户信息
export const getUserToken = (loginForm) => {
  return async (dispatch) => {
    // 发送异步请求
    const res = await getUserTokenAPI(loginForm);
    // 提交同步action进行token的存入
    dispatch(setToken(res.data));
  };
};

/** 获取用户信息 */
export const getUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfoAPI();
    dispatch(setUserInfo(res.data));
  };
};

export default userStore.reducer;
